package com.baitengsoft.patentapimonitor.api.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baitengsoft.patentapimonitor.api.dao.FileUploadRecordDao;
import com.baitengsoft.patentapimonitor.api.entity.FileUploadRecordEntity;
import com.baitengsoft.patentapimonitor.api.entity.PacPatentinfoEntity;
import com.baitengsoft.patentapimonitor.api.service.CfgDictionaryService;
import com.baitengsoft.patentapimonitor.api.service.FileUploadRecordService;
import com.baitengsoft.patentapimonitor.api.service.PacPatentinfoService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import com.baitengsoft.patentapimonitor.common.utils.WebExcelUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.poi.ss.usermodel.CellType.NUMERIC;

/**
 * @author Chen 2018/2/8
 */
@Service
public class FileUploadRecordServiceImpl implements FileUploadRecordService {
    @Autowired
    private FileUploadRecordDao fileUploadRecordDao;
    @Autowired
    private PacPatentinfoService pacPatentinfoService;
    @Autowired
    private CfgDictionaryService cfgDictionaryService;

    private static final List<Integer> checkColumn = Arrays.asList(0,1,2);
    @Override
    public PageResult<FileUploadRecordEntity> queryList(Integer platformid, SearchParam param) {
        Page<Object> page = PageHelper.startPage(param.getPageNumber(), param.getPageSize());
        Example example = new Example(FileUploadRecordEntity.class);
        example.setOrderByClause(" createdate desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("platformid",platformid);
        List<FileUploadRecordEntity> entities = fileUploadRecordDao.selectByExample(example);
        Long total = page.getTotal();
        return new PageResult<FileUploadRecordEntity>(entities,param.getPageNumber(),param.getPageSize(),total.intValue());
    }



    @Override
    public Res delete(Integer platformid, Integer id) {
        FileUploadRecordEntity e = fileUploadRecordDao.selectByPrimaryKey(id);
        if (e == null || e.getPlatformid() == null|| !e.getPlatformid().equals(platformid))
            return Res.error("参数有误");
        if (StringUtils.isBlank(e.getFileurl())){
            fileUploadRecordDao.delete(e);
            return Res.ok();
        }else{
            String uploadFilePath = WebExcelUtils.getUploadFilePath(platformid, e.getFileurl());
            File file = new File(uploadFilePath);
            if (file.exists()){
                boolean delete = file.delete();
                if (!delete){
                    return Res.error("删除有误");
                }
            }
            fileUploadRecordDao.delete(e);
            return Res.ok();
        }
    }

    @Override
    public Res download(Integer platformid, String  fileUrl, HttpServletResponse response) {
        Example example = new Example(FileUploadRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("fileurl",fileUrl);
        List<FileUploadRecordEntity> entities = fileUploadRecordDao.selectByExample(example);
        if (entities == null || entities.size() <1) return Res.error("参数有误");
        FileUploadRecordEntity entity = entities.get(0);
        String uploadFilePath = WebExcelUtils.getUploadFilePath(platformid, fileUrl + ".xls");
        try {
            WebExcelUtils.download(uploadFilePath,entity.getTitle(),response);
        } catch (Exception e1) {
            e1.printStackTrace();
            return Res.error("下载失败");
        }
        return Res.ok();
    }

    @Override
    public Res importPatInfoByPlatforomId(Integer platformid, MultipartFile file)  throws Exception{
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
        //检查是否存在空
        CheckResult checkResult = checkExcelData(hssfWorkbook);
        if (!checkResult.isSuccess)
            return Res.error(checkResult.getErrorMessage());
        //插入Info表
        CheckResult insertResult = insertPatInfoByImportFile(platformid,file);
        if (!checkResult.isSuccess)
            return Res.error(checkResult.getErrorMessage());
        //保存文件到服务器
        CheckResult saveResult = saveImportFile(platformid,file);
        if (!checkResult.isSuccess)
            return Res.error(checkResult.getErrorMessage());
        return Res.ok();
    }

    private CheckResult saveImportFile(Integer platformid,MultipartFile file) {
        String fileUrl = WebExcelUtils.getUUID();
        //保存文件到本地
        String originalFilename = file.getOriginalFilename();
        try {
            File filePath = new File(WebExcelUtils.getUploadFilePath1(platformid));
            if (filePath.exists()) {
                if (filePath.isDirectory()) {
                } else {
                }
            } else {
                filePath.mkdir();
             }
            String path = WebExcelUtils.getUploadFilePath(platformid,fileUrl)+".xls";
            FileOutputStream fs=new FileOutputStream(path);
            byte[] buffer =new byte[1024*1024];
            int bytesum = 0;
            int byteread = 0;
            InputStream stream = file.getInputStream();
            while ((byteread=stream.read(buffer))!=-1)
            {
                bytesum+=byteread;
                fs.write(buffer,0,byteread);
                fs.flush();
            }
            fs.close();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return new CheckResult("上传文件失败");
        }
        //保存上传记录
        FileUploadRecordEntity entity = new FileUploadRecordEntity();
        entity.setPlatformid(platformid);
        entity.setTitle(originalFilename);
        entity.setCreatedate(new Date());
        entity.setFileurl(fileUrl);
        entity.setIssuccess(true);
        entity.setMemo("");
        fileUploadRecordDao.insert(entity);
        return new CheckResult(true);
    }

    /**
     * 进行数据获取，插入到Insert表中
     */
    private CheckResult insertPatInfoByImportFile(Integer platformid,MultipartFile file) {
        try {
            ExcelReader reader;
            reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> lists = reader.read(1);
            List<PacPatentinfoEntity> entities= new ArrayList<>();
            for (List<Object> row :lists){
                PacPatentinfoEntity entity = new PacPatentinfoEntity();
                entity.setPatnum(row.get(0)+"");
                entity.setPatname((String)row.get(1));
                entity.setApplyperson((String)row.get(2));
                entity.setPatappdate((Date)row.get(3));
                entity.setPataddress((String)row.get(4));
                if(row.get(5).equals("发明专利")){
                    entity.setPattypename(1);
                }else if(row.get(5).equals("实用新型")){
                    entity.setPattypename(2);
                }else {
                    entity.setPattypename(3);
                }
                String b = (String)row.get(6);
                String a = cfgDictionaryService.getValueByCodeAndName("1004",b);
                entity.setApplypersontype(Integer.parseInt(a));
                entity.setAgencyname((String)row.get(7));
                entity.setPlatformid(platformid);
                entities.add(entity);
            }
            pacPatentinfoService.saveInportPatInfos(entities);
        } catch (IOException e) {
            return new CheckResult("数据获取失败,请联系管理员");
        }
        return new CheckResult(true);
    }

    /**
     * 检查必填以及数据格式
     */
    private CheckResult checkExcelData(HSSFWorkbook hssfWorkbook) {
        HSSFSheet sheet = hssfWorkbook.getSheet("Sheet1");
        if (sheet == null)
            return new CheckResult("无法找到Sheet1");
        HSSFRow row = null;
        //得到总行数，总列数
        int rowNum = sheet.getLastRowNum();
        if (rowNum == 0){
            return new CheckResult("无数据");
        }
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            Iterator<Integer> iterator = checkColumn.iterator();
            while (iterator.hasNext()){
                Integer column = iterator.next();
                HSSFCell cell0 = row.getCell(column);
                //判断各个单元格是否为空
                CheckResult checkResult = checkRowError(cell0, i , column);
                if (!checkResult.isSuccess){
                    return checkResult;
                }
            }
        }
        return new CheckResult(true);
    }

    /**
     * 判断某行某列有问题
     */
    private CheckResult checkRowError(HSSFCell cell, int rowNum, int cell_num){
        //判断各个单元格是否为空
        if(cell==null||cell.equals("")||cell.getCellType() ==HSSFCell.CELL_TYPE_BLANK){
            return new CheckResult("出错啦！请检查第"+(rowNum+1)+"行第"+(cell_num+1)+"列。"+"必填！");
        }
        if (cell_num == 3 ){
            if (!cell.getCellTypeEnum().equals(NUMERIC)){
                return new CheckResult("日期格式出错！请检查第"+(rowNum+1)+"行第"+(cell_num+1)+"列。");
            }else {
                if (!HSSFDateUtil.isCellDateFormatted(cell)){
                    return new CheckResult("日期格式出错！请检查第"+(rowNum+1)+"行第"+(cell_num+1)+"列。");
                }
            }
        }
        return new CheckResult(true);
    }

//         case HSSFCell.CELL_TYPE_NUMERIC: // 数字
//            //如果为时间格式的内容
//            if (HSSFDateUtil.isCellDateFormatted(cell)) {
//        //注：format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制，若要24小时制，则把小h变为H即可，yyyy-MM-dd HH:mm:ss
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        value=sdf.format(HSSFDateUtil.getJavaDate(cell.
//                getNumericCellValue())).toString();
//        break;
//    } else {
//        value = new DecimalFormat("0").format(cell.getNumericCellValue());
//    }
//


    class CheckResult {
        Boolean isSuccess;
        String errorMessage;

        public CheckResult(String errorMessage) {
            this.isSuccess = false;
            this.errorMessage = errorMessage;
        }

        public CheckResult(Boolean isSuccess) {
            this.isSuccess = isSuccess;
        }

        public Boolean isSuccess() {
            return isSuccess;
        }

        public void setIsSuccess(Boolean success) {
            isSuccess = success;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }
    }
}
